<script setup lang="ts">
import dayjs from 'dayjs';
import { reactive, onMounted, computed } from 'vue';
import { getCurrentInstance, showModal, redirectTo, showLoading, hideLoading } from '@tarojs/taro';
import {
  MY_DETAIL,
  CANCEL,
  ACCEPT,
  REJECT,
  OUT,
} from '/@/api/modules/visitor/visitor-appointment-api';
import { getSysImgUrl } from '/@/utils/index';
import { appEvents } from '/@/utils/events';
import { Desensitized } from '/@/utils/desensitized';
import { VisitorAppointmentDetailState } from './index.d';

/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as unknown as {
  id: string;
};

const state = reactive<VisitorAppointmentDetailState>({
  startTime: undefined,
  endTime: undefined,
  purpose: '',
  list: [],
  tip: '加载中...',
  acceptPopupIsShow: false,
  rejectPopupIsShow: false,
  auditOpinion: '',
  auditStatus: undefined,
  cancelStatus: undefined,
  signOut: undefined,
  signIn: undefined,
  signOutTime: undefined,
  signOutType: undefined,
});

/**
 * @function 取消预约
 * @param id -预约id
 */
function cancel(id: string) {
  if (!id) return;

  showModal({
    content: '确认取消预约？',
    success: ({ confirm }) => {
      if (!confirm) return;

      showLoading();
      CANCEL({ id }).then(() => {
        appEvents.trigger('visitorAppointmentStatusChange', { id: params.id, status: 5 });
        hideLoading();
        redirectTo({
          url: `/pages/visitor/appointment-detail/index?id=${params.id}&auditStatus=5`,
        });
      });
    },
  });
}

/**
 * @function 同意预约
 * @param id -预约id
 * @param auditOpinion -审批意见
 */
function accept(id: string, auditOpinion: string) {
  if (!id) return;

  showLoading();
  ACCEPT({ id, auditStatus: 1, auditOpinion }).then(() => {
    state.auditOpinion = '';
    appEvents.trigger('visitorAppointmentStatusChange', { id: params.id, status: 1 });
    hideLoading();
    redirectTo({
      url: `/pages/visitor/appointment-detail/index?id=${params.id}&auditStatus=1`,
    });
  });
}

/**
 * @function 签离
 * @param id -预约id
 * @param auditOpinion -审批意见
 */
function out(id: string) {
  if (!id) return;

  showModal({
    content: '确认访客签离？',
    success: ({ confirm }) => {
      if (!confirm) return;

      showLoading();
      OUT({ id }).then(() => {
        state.auditOpinion = '';
        appEvents.trigger('visitorAppointmentStatusChange', {
          id: params.id,
          status: 1,
          signOut: 1,
        });
        hideLoading();
        redirectTo({
          url: `/pages/visitor/appointment-detail/index?id=${params.id}&auditStatus=1&signOut=1`,
        });
      });
    },
  });
}

/**
 * @function 拒绝预约
 * @param id -预约id
 * @param auditOpinion -审批意见
 */
function reject(id: string, auditOpinion: string) {
  if (!id) return;

  showModal({
    content: '确认拒绝预约？',
    success: ({ confirm }) => {
      if (!confirm) return;

      showLoading();
      REJECT({ id, auditStatus: 2, auditOpinion }).then(() => {
        state.auditOpinion = '';
        appEvents.trigger('visitorAppointmentStatusChange', { id: params.id, status: 2 });
        hideLoading();
        redirectTo({
          url: `/pages/visitor/appointment-detail/index?id=${params.id}&auditStatus=2`,
        });
      });
    },
  });
}

onMounted(() => {
  MY_DETAIL({ id: params.id })
    .then((res) => {
      state.startTime = res.startTime;
      state.endTime = res.endTime;
      state.purpose = res.purpose;
      state.list = res.content;
      state.auditStatus = res.auditStatus;
      state.cancelStatus = res.cancelStatus;
      state.signOut = res.signOut;
      state.signOutTime = res.signOutTime;
      state.signOutType = res.signOutType;
      state.signIn = res.signIn;
      state.tip = '';
    })
    .catch((err) => {
      state.tip = err.comResp.tip || err.comResp.err;
    });
});

const signOutContent = computed(() => {
  const time = state.signOutTime ? dayjs(state.signOutTime).format('MM-DD HH:mm:ss') : '-';
  let type = '';
  switch (state.signOutType) {
    case 1:
      type = '手动签离';
      break;
    case 2:
      type = '访客机签离';
      break;
    case 3:
      type = '超时签离';
      break;
  }
  return time + ' ' + type;
});
</script>

<template>
  <view class="visitor-appointment-detail app-page--1">
    <app-navbar title="预约详情" />
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="visitor-appointment-detail__wrapper">
        <nut-form v-if="state.startTime" class="visitor-appointment-detail__form">
          <nut-form-item label="预计来访时间" label-align="left">
            <view>
              {{ state.startTime ? dayjs(state.startTime).format('YYYY-MM-DD HH:mm:ss') : '-' }}
            </view>
          </nut-form-item>
          <nut-form-item label="预计离开时间" label-align="left">
            <view>
              {{ state.endTime ? dayjs(state.endTime).format('YYYY-MM-DD HH:mm:ss') : '-' }}
            </view>
          </nut-form-item>
          <nut-form-item label="来访事由" label-align="left">
            <view>{{ state.purpose || '-' }}</view>
          </nut-form-item>
        </nut-form>

        <nut-form
          v-for="item in state.list"
          :key="item.id"
          class="visitor-appointment-detail__form"
        >
          <nut-form-item label="姓名" label-align="left">
            <view class="visitor-appointment-detail__name-wrapper">
              <view class="visitor-appointment-detail__name-wrapper--left">
                {{ item.personName || '未填写' }}
              </view>
              <nut-tag v-if="item.attentionPerson === 1" type="danger">重点人员</nut-tag>
            </view>
          </nut-form-item>
          <nut-form-item label="性别" label-align="left">
            <view>{{ item.sex ? { 1: '男', 2: '女' }[item.sex] : '未填写' }}</view>
          </nut-form-item>
          <nut-form-item label="联系电话" label-align="left">
            <view>{{ Desensitized.desensitizedPhone(item.phone) || '未填写' }}</view>
          </nut-form-item>
          <nut-form-item label="身份证" label-align="left">
            <view>{{ Desensitized.desensitizedIdNo(item.idNo) || '未填写' }}</view>
          </nut-form-item>
          <nut-form-item label="车牌号" label-align="left">
            <view>{{ item.carNo || '未填写' }}</view>
          </nut-form-item>
          <nut-form-item label="单位" label-align="left">
            <view>{{ item.visitorWorkUint || '未填写' }}</view>
          </nut-form-item>
          <nut-form-item label="头像照片" label-align="left">
            <image
              v-if="item.fileUrl"
              class="visitor-appointment-detail__avatar"
              :src="getSysImgUrl(item.fileUrl || '')"
            />
            <view v-else>未上传</view>
          </nut-form-item>
        </nut-form>
      </view>

      <view class="app-page__list-tips">
        <text v-if="state.tip">{{ state.tip }}</text>
        <text v-if="!state.tip && (!state.startTime || !state.endTime)"
          >访客暂未上传信息，请稍后查看</text
        >
      </view>
    </scroll-view>

    <view
      v-if="
        state.auditStatus &&
        [1, 2, 4, 5].includes(state.auditStatus) &&
        state.cancelStatus === 2 &&
        state.signOut === 2
      "
      class="visitor-appointment-detail__footer"
    >
      <nut-button
        v-if="state.signIn === 2"
        class="visitor-appointment-detail__footer-btn"
        type="danger"
        @click="cancel(params.id)"
      >
        取消预约
      </nut-button>
      <nut-button
        v-if="state.signIn === 1 && state.signOut === 2"
        class="visitor-appointment-detail__footer-btn"
        type="default"
        @click="out(params.id)"
      >
        访客签离
      </nut-button>
    </view>
    <view
      v-else-if="
        state.auditStatus === 3 && state.cancelStatus === 2 && state.list && state.list.length
      "
      class="visitor-appointment-detail__footer"
    >
      <nut-row :gutter="20">
        <nut-col :span="12">
          <nut-button
            type="info"
            block
            @click="
              () => {
                state.acceptPopupIsShow = true;
              }
            "
          >
            同意
          </nut-button>
        </nut-col>
        <nut-col :span="12">
          <nut-button
            block
            @click="
              () => {
                state.rejectPopupIsShow = true;
              }
            "
          >
            拒绝
          </nut-button>
        </nut-col>
      </nut-row>
    </view>
    <view v-if="state.cancelStatus === 1" class="visitor-appointment-detail__footer">
      <view class="visitor-appointment-detail__footer-txt">已取消</view>
    </view>
    <view v-if="state.signOut === 1" class="visitor-appointment-detail__footer">
      <view class="visitor-appointment-detail__footer-txt">
        <view>已签离</view>
        <view class="visitor-appointment-detail__footer-sub-txt">{{ signOutContent }}</view>
      </view>
    </view>

    <nut-popup
      v-model:visible="state.acceptPopupIsShow"
      :style="{ height: 'auto' }"
      position="bottom"
      closeable
    >
      <view class="app-popup__header">同意访客预约申请</view>
      <view class="app-popup__wrapper">
        <nut-textarea
          v-model="state.auditOpinion"
          limit-show
          max-length="100"
          placeholder="请输入审批意见"
          :rows="10"
        />
      </view>
      <view class="app-popup__footer">
        <nut-button type="primary" block @click="accept(params.id, state.auditOpinion)">
          确认
        </nut-button>
      </view>
    </nut-popup>

    <nut-popup
      v-model:visible="state.rejectPopupIsShow"
      :style="{ height: 'auto' }"
      position="bottom"
      closeable
    >
      <view class="app-popup__header">拒绝访客预约申请</view>
      <view class="app-popup__wrapper">
        <nut-textarea
          v-model="state.auditOpinion"
          limit-show
          max-length="100"
          placeholder="请输入审批意见"
          :rows="10"
        />
      </view>
      <view class="app-popup__footer">
        <nut-button block @click="reject(params.id, state.auditOpinion)"> 确认 </nut-button>
      </view>
    </nut-popup>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
